package com.rim.samples.device.helloworlddemo;

import java.io.IOException;
import java.io.InputStream;

import javax.microedition.io.DatagramConnection;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.PlayerListener;


public class RecvThread extends Thread implements PlayerListener
{
    private Player player;
    
    private DatagramConnection mConnection;
    
    private InputStream mInput;
    
    public void run()
    {
		mInput = new MyDataSource(new byte[100 * 1024]);
		
        try
        {
            player = Manager.createPlayer(mInput, "audio/x-pcm");
            player.start();
        }
        catch (IOException e)
        {
            Log.d("", "IOException:" + e.toString());
            e.printStackTrace();
        }
        catch (MediaException e)
        {
            Log.d("", "MediaException:" + e.toString());
            e.printStackTrace();
        }
	}
    
    public void stop()
    {
        if (mConnection != null)
        {
            try
            {
                mConnection.close();
            }
            catch (IOException e1)
            {
                System.out.println("close Connection exception");
                e1.printStackTrace();
            }
        }
        
        if (player != null)
        {
            try
            {
                if (player.getState() == Player.STARTED)
                {
                    player.stop();
                }
                if (player.getState() != Player.CLOSED)
                {
                    player.close();
                }
            }
            catch (MediaException e)
            {
                System.out.println("Error stopping reveive stream" + e);
            }
        }
        
    }
    
    public void playerUpdate(Player player, String event, Object eventData)
    {
        System.out.println("playerUpdate, " + event);
        if (event == PlayerListener.BUFFERING_STARTED)
        {
            // mBuffering = true;
        }
        else if (event == PlayerListener.DEVICE_UNAVAILABLE)
        {
            // pausing both player and recorder
            
        }
        else if (event == PlayerListener.DEVICE_AVAILABLE)
        {
            // starting both player and recorder
            try
            {
                start();
            }
            catch (Throwable e)
            {
                e.printStackTrace();
            }
        }
    }
}
